package com.ui;

import com.service.GroupService;
import com.model.Group;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;


public class GroupManagementUI extends JFrame {
    private GroupService groupService;
    private JTable table;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private String currentClass;

    public GroupManagementUI(GroupService groupService, String currentClass) {
        this.groupService = groupService;
        this.currentClass = currentClass;
        setTitle("小组管理");
        setSize(600, 400);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new BorderLayout());

        // 创建输入框和按钮
        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(20);
        JButton searchButton = new JButton("查询");
        JButton deleteButton = new JButton("删除");
        JButton backButton = new JButton("返回");

        inputPanel.add(searchField);
        inputPanel.add(searchButton);
        inputPanel.add(deleteButton);
        inputPanel.add(backButton);

        panel.add(inputPanel, BorderLayout.NORTH);

        // 创建表格模型和表格
        tableModel = new DefaultTableModel(new Object[]{"小组ID", "小组名称"}, 0);
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);

        panel.add(scrollPane, BorderLayout.CENTER);

        add(panel);

        // 查询按钮事件
        searchButton.addActionListener(e -> searchGroups());

        // 删除按钮事件
        deleteButton.addActionListener(e -> deleteSelectedGroup());

        // 返回按钮事件
        backButton.addActionListener(e -> dispose());

        setVisible(true);
    }

    private void searchGroups() {
        String searchText = searchField.getText().trim();

        List<Group> groups;
        if (!searchText.isEmpty()) {
            groups = groupService.getGroupListByName(searchText);
        } else {
            groups = groupService.getAllGroupsForClass(currentClass);
        }
        tableModel.setRowCount(0); // 清空表格
        for (Group group : groups) {
            tableModel.addRow(new Object[]{group.getId(), group.getName()});
        }
    }

    private void deleteSelectedGroup() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            int groupId = (int) tableModel.getValueAt(selectedRow, 0);
            groupService.deleteGroup(groupId);
            tableModel.removeRow(selectedRow);
            JOptionPane.showMessageDialog(this, "小组删除成功");
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一个小组", "警告", JOptionPane.WARNING_MESSAGE);
        }
    }
}